package com.lc.projects.unit.thread.part04.test1;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

//运行多个任务 并处理第一个结果 ThreadPoolExecutor
public class Test2 {
	public static void main(String[] args) {
		ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
		UserValidator u1 = new UserValidator("LDP");
		UserValidator u2 = new UserValidator("BBC");
		TaskValidate t1 = new TaskValidate("LC", "A", u1);
		TaskValidate t2 = new TaskValidate("LC", "A", u2);

		
		List<TaskValidate> list = new ArrayList<>();
		list.add(t1);
		list.add(t2);
		
		String result = null ;
		
		try {
			result = executor.invokeAny(list);
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
		executor.shutdown();
		System.out.println("Main: "+result);
	}
}

class UserValidator {
	private String name;

	public UserValidator(String name) {
		super();
		this.name = name;
	}

	public boolean validate(String username, String password) {
		Random random = new Random();
		long duration = (long) (Math.random() * 10);
		try {
			System.out.println(name + " Validate user during " + duration);
			TimeUnit.SECONDS.sleep(duration);
		} catch (InterruptedException e) {
			e.printStackTrace();
			return false;
		}

		return random.nextBoolean();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

class TaskValidate implements Callable<String> {
	private String username;
	private String password;
	private UserValidator userValidator;

	public TaskValidate(String username, String password, UserValidator userValidator) {
		super();
		this.username = username;
		this.password = password;
		this.userValidator = userValidator;
	}

	@Override
	public String call() throws Exception {
		if (!userValidator.validate(username, password)) {
			throw new Exception(userValidator.getName() + " The user has not been found.");
		}
		return userValidator.getName();
	}

}